package com.plum.netty.demo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

import static io.netty.buffer.ByteBufUtil.appendPrettyHexDump;
import static io.netty.util.internal.StringUtil.NEWLINE;

public class TestByteBuf {
    public static void main(String[] args) {
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        buffer.writeBytes(new byte[]{1, 2, 3, 4});
        log(buffer);
        buffer.writeInt(10);
        log(buffer);
    }
//    read index:0 write index:5 capacity:5
//            +-------------------------------------------------+
//            |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
//            +--------+-------------------------------------------------+----------------+
//            |00000000| 01 02 03 04 05                                  |.....           |
//            +--------+-------------------------------------------------+----------------+
//    read index:0 write index:5 capacity:5
//            +-------------------------------------------------+
//            |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
//            +--------+-------------------------------------------------+----------------+
//            |00000000| 06 07 08 09 0a                                  |.....           |
//            +--------+-------------------------------------------------+----------------+
//            ===========修改原buffer中的值===========
//            ===========打印slice1===========
//    read index:0 write index:5 capacity:5
//            +-------------------------------------------------+
//            |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
//            +--------+-------------------------------------------------+----------------+
//            |00000000| 05 02 03 04 05                                  |.....           |
//            +--------+-------------------------------------------------+----------------+


    private static void log(ByteBuf buffer) {
        int length = buffer.readableBytes();
        int rows = length / 16 + (length % 15 == 0 ? 0 : 1) + 4;
        StringBuilder buf = new StringBuilder(rows * 80 * 2)
                .append("read index:").append(buffer.readerIndex())
                .append(" write index:").append(buffer.writerIndex())
                .append(" capacity:").append(buffer.capacity())
                .append(NEWLINE);
        appendPrettyHexDump(buf, buffer);
        System.out.println(buf.toString());
    }
}
